package com.zzf.concurrent.example.design.pattern.active.object;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

/**
 * @author GaoFeng2017
 * @date 2019/9/11 14:36
 */
@Slf4j
class ActivationQueue {

    private final int maxRequest;
    private static final int DEFAULT_MAX_QUEUE = 10;
    private LinkedList<MethodRequest> requests;

    ActivationQueue() {
        this(DEFAULT_MAX_QUEUE);
    }

    private ActivationQueue(int maxRequest) {
        this.maxRequest = maxRequest;
        this.requests = new LinkedList<>();
    }

    synchronized void put(MethodRequest request) {

        while (requests.size() >= maxRequest) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                log.error("fail to put request", e);
            }
        }

        this.requests.addLast(request);
        this.notifyAll();
    }

    synchronized MethodRequest poll() {

        while (this.requests.peek() == null) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                log.error("fail to get request", e);
            }
        }

        MethodRequest request = this.requests.poll();
        this.notifyAll();
        return request;
    }
}
